"use client";


import * as icons from "@ant-design/icons";
import {
  menuAdd,
  menuDelete,
  menuList,
  menuUpdate,
} from "@/app/actions/menu_action";
import { MenusItem, geneRateMenuTree } from "@/components/utilUi";
import { useUserStore } from "@/store/userStore";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import {
  Space,
  Table,
  TableColumnsType,
  Button,
  Modal,
  Form,
  Input,
  Select,
  TreeSelect,
  Tag,
  message,
} from "antd";
import { useEffect, useState } from "react";
import { Menu } from "@prisma/client";

export default function MenuPage() {
  const [formVal, setFormVal] = useState<Partial<Menu>>({});
  const [treeData, setTreeData] = useState<any[]>([]);
  const [form] = Form.useForm();
  const columns: TableColumnsType = [
    {
      title: "名称",
      key: "name",
      render: (record) => {
        return (
          <span>
            {record.icon}
            <span className=" ml-2">{record.name}</span>
          </span>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
    },
    {
      title: "路径",
      dataIndex: "path",
      key: "path",
    },
    {
      title: "操作",
      key: "operation",
      render: (record) => (
        <Space size="middle">
          <Button
            size="small"
            type="primary"
            onClick={() => {
              setFormVal(record);
              form.setFieldsValue(record);
              if (record.icon && record.icon.type) {
                form.setFieldValue("icon", record.icon.type.render.name);
              }
              showModal();
            }}
          >
            编辑
          </Button>
          <Button
            size="small"
            onClick={() => {
              modal.confirm({
                title: "提示",
                icon: <ExclamationCircleOutlined />,
                content: "您确定要删除吗?",
                onOk: async () => {
                  const result = await menuDelete({ id: record.id });

                  if (result.data) {
                    message.success("删除成功");
                    fetMenu();
                  }
                },
                okText: "确认",
                cancelText: "取消",
              });
            }}
            danger
            type="dashed"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const iconKey = Object.keys(icons).filter((it) => !it.endsWith("TwoTone"));

  const treeItemList = (
    list: (MenusItem & { id: number; name: string })[]
  ): any => {
    return list.map((item) => {
      return {
        value: item.id,
        title: item.name,
        children: item.children
          ? treeItemList(item.children as any)
          : undefined,
      };
    });
  };
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const [menus, setMenus] = useState<MenusItem[]>([]);
  const fetMenu = async () => {
    const menuResult = await menuList();
    if (menuResult.data) {
      const menuTemp = geneRateMenuTree(menuResult.data || [], true);
      setMenus(menuTemp);
      const treeList = treeItemList(menuTemp as any);
      setTreeData(treeList);
    }
  };
  const [modal, contextHolder] = Modal.useModal();
  const onFinish = async (value: any) => {
    let fun = menuAdd;
    if (formVal.id) {
      value.id = formVal.id;
      fun = menuUpdate;
    }
    modal.confirm({
      title: "提示",
      icon: <ExclamationCircleOutlined />,
      content: "您确定要修改吗?",
      onOk: async () => {
        const result = await fun(value);
        if (result.data) {
          message.success("操作成功");
          fetMenu();
          handleCancel();
        }
      },
      okText: "确认",
      cancelText: "取消",
    });
  };

  const [userInfo] = useUserStore((state) => [state.user]);
  const [isModalOpen, setIsModalOpen] = useState(false);

  useEffect(() => {
    fetMenu();
  }, []);
  return (
    <div className="h-full">
      {contextHolder}
      <Button
        className="m-2"
        onClick={() => {
          setFormVal({});
          form.resetFields()
          showModal();
        }}
        type="primary"
      >
        新增菜单
      </Button>
      <Table columns={columns} dataSource={menus} pagination={false} />
      <Modal
        title="菜单编辑"
        footer={null}
        open={isModalOpen}
        onCancel={handleCancel}
      >
        <Form
          name="nest-messages"
          onFinish={onFinish}
          style={{ maxWidth: 600 }}
          form={form}
        >
          <Tag color="red">不选择默认创建一级菜单</Tag>
          <Form.Item name="parentId" label="菜单类别">
            <TreeSelect treeData={treeData} />
          </Form.Item>

          <Form.Item name="name" label="菜单名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="icon" label="菜单图标" rules={[{ required: true }]}>
            <Select
              showSearch
              options={iconKey.map((item, index) => {
                const Icon = (icons as any)[item];
                if (Icon.render) {
                  return {
                    value: item,
                    label: (
                      <div>
                        <Icon style={{ color: "black" }} />
                        <span className="ml-2">{item}</span>
                      </div>
                    ),
                  };
                }
                return {};
              })}
            ></Select>
          </Form.Item>
          <Form.Item name="path" label="菜单路径" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item>
            <div className="text-right">
              <Space>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      {/* <XTable update={update} deleteItem={deleteItem} getList={getList} columns={columns}></XTable> */}
    </div>
  );
}
